<template>
  <div class="process-instance-container">
    <div class="blod text-xl">流程实例</div>
    <!-- 搜索栏 -->
    <div class="bg-white p-4 rounded-lg shadow mb-4">
      <el-form :model="queryForm" inline>
        <el-form-item label="流程实例ID">
          <el-input v-model="queryForm.processInstanceId" placeholder="请输入流程实例ID" clearable/>
        </el-form-item>
        <el-form-item label="流程定义">
          <el-select v-model="queryForm.processDefinitionKey" placeholder="请选择流程" clearable>
            <el-option v-for="def in processDefinitions" :key="def.key" :label="def.name" :value="def.key"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryForm.status" placeholder="请选择状态" clearable>
            <el-option label="运行中" value="active"/>
            <el-option label="已结束" value="completed"/>
            <el-option label="已挂起" value="suspended"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 流程实例列表 -->
    <div class="bg-white p-6 rounded-lg shadow">
      <el-table :data="processInstances" stripe v-loading="loading">
        <el-table-column prop="id" label="实例ID" width="120"/>
        <el-table-column prop="processDefinitionName" label="流程名称"/>
        <el-table-column prop="processDefinitionKey" label="流程Key"/>
        <el-table-column prop="startUserId" label="发起人" width="120"/>
        <el-table-column prop="startTime" label="开始时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.startTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="endTime" label="结束时间" width="180">
          <template #default="scope">
            {{ scope.row.endTime ? formatDate(scope.row.endTime) : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row)">
              {{ getStatusText(scope.row) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" >
          <template #default="scope">
            <el-button @click="handleViewDetail(scope.row)" type="text" size="small">查看进度</el-button>
            <el-button @click="handleViewTasks(scope.row)" type="text" size="small" v-if="scope.row.status === 'active'"
            >
              处理任务
            </el-button>
            <el-button @click="handleActivate(scope.row)" type="success" text size="small"
                       v-if="scope.row.status === 'suspended'">
              激活
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="mt-4 flex justify-end">
        <el-pagination
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.size"
            :total="pagination.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 流程进度对话框 -->
    <el-dialog title="流程进度" v-model="showProgressDialog" width="90%" top="5vh">
      <div v-if="currentInstance" class="progress-container">
        <!-- 流程图 -->
        <div class="mb-6">
          <h3 class="text-lg font-semibold mb-4">流程图</h3>
          <div class="bpmn-diagram border rounded-lg p-4 bg-gray-50">
            <div class="text-center text-gray-500 py-8">
              BPMN流程图显示区域
              <div class="mt-2 text-sm"> 当前节点:
                <el-tag type="primary">{{ getCurrentActivity() }}</el-tag>
              </div>
            </div>
          </div>
        </div>

        <!-- 执行流 -->
        <div class="mb-6">
          <h3 class="text-lg font-semibold mb-4">执行流</h3>
          <el-timeline>
            <el-timeline-item v-for="(activity, index) in activityHistory" :key="index"
                              :timestamp="formatDate(activity.startTime)" :type="getTimelineType(activity)"
                              :hollow="!activity.endTime"
            >
              <div class="flex justify-between items-center">
                <div><strong>{{ activity.activityName }}</strong> <span
                    class="ml-2 text-gray-500">     ({{ !activity.endTime ? '当前节点' : '已完成' }})   </span></div>
                <el-tag :type="getActivityTagType(activity)"> {{ activity.assignee || '系统任务' }}</el-tag>
              </div>
              <div v-if="activity.durationInMillis" class="mt-1 text-gray-600"> 耗时:
                {{ formatDuration(activity.durationInMillis) }}
              </div>
            </el-timeline-item>
          </el-timeline>
        </div>

        <!-- 流程变量 -->
        <div>
          <h3 class="text-lg font-semibold mb-4">流程变量</h3>
          <el-table :data="formatVariables(currentInstance.variables)" border>
            <el-table-column prop="name" label="变量名" width="200"/>
            <el-table-column prop="value" label="变量值"/>
          </el-table>
        </div>
      </div>
    </el-dialog>

    <!-- 任务处理对话框 -->
    <el-dialog title="处理任务" v-model="showTaskDialog" width="600px">
      <div v-if="currentInstance">
        <el-alert
            title="当前流程实例任务"
            type="info"
            :closable="false"
            class="mb-4"
        />

        <el-table :data="activeTasks" border>
          <el-table-column prop="name" label="任务名称"/>
          <el-table-column prop="assignee" label="负责人" width="120"/>
          <el-table-column prop="createTime" label="创建时间" width="180">
            <template #default="scope">
              {{ formatDate(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="scope">
              <el-button @click="handleCompleteTask(scope.row)" type="primary" text size="small"
                         v-if="scope.row.assignee === currentUser">
                处理
              </el-button>
              <el-button @click="handleClaimTask(scope.row)" type="success" text size="small" v-if="!scope.row.assignee"
              > 认领
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 完成任务表单 -->
        <div v-if="selectedTask" class="mt-6 p-4 border rounded-lg">
          <h4 class="font-semibold mb-4">处理任务: {{ selectedTask.name }}</h4>
          <el-form :model="completeForm" label-width="80px">
            <el-form-item label="审批结果">
              <el-radio-group v-model="completeForm.approved">
                <el-radio :label="true">通过</el-radio>
                <el-radio :label="false">拒绝</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="审批意见">
              <el-input type="textarea" v-model="completeForm.comment" placeholder="请输入审批意见" :rows="3"
              />
            </el-form-item>
            <el-form-item>
              <el-button @click="selectedTask = null">取消</el-button>
              <el-button type="primary" @click="handleCompleteTaskSubmit" :loading="submitting"> 提交
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import {onMounted, reactive, ref} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import axios from "axios";
import {API_BASE_URL} from "@/assets/_const";
// API基础URL

// 数据
const processInstances = ref([])
const activeTasks = ref([])
const activityHistory = ref([])
const loading = ref(false)
const submitting = ref(false)
const showProgressDialog = ref(false)
const showTaskDialog = ref(false)
const currentInstance = ref(null)
const selectedTask = ref(null)
const currentUser = ref('admin')

const processDefinitions = ref([
  {key: 'leave_process', name: '请假流程'},
  {key: 'expense_process', name: '报销流程'}
])

// 分页
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 表单
const queryForm = reactive({
  processInstanceId: '',
  processDefinitionKey: '',
  status: ''
})

const completeForm = reactive({
  approved: true,
  comment: ''
})

// 生命周期
onMounted(() => {
  loadProcessInstances()
})

// 方法
const loadProcessInstances = async () => {
  loading.value = true
  try {
    const response = await axios.post(`${API_BASE_URL}/api/process/instance/list`, {
      processInstanceId: queryForm.processInstanceId,
      processDefinitionKey: queryForm.processDefinitionKey,
      status: queryForm.status,
      page: pagination.current,
      size: pagination.size
    })

    processInstances.value = response.data.list
    pagination.total = response.data.total
  } catch (error) {
    console.error('加载流程实例失败:', error)
    ElMessage.error('加载失败')
  } finally {
    loading.value = false
  }
}

const loadProcessInstanceDetail = async (processInstanceId) => {
  try {
    const response = await axios.get(`${API_BASE_URL}/api/process/instance/${processInstanceId}`)
    currentInstance.value = response.data
  } catch (error) {
    console.error('加载流程实例详情失败:', error)
    ElMessage.error('加载详情失败')
  }
}

const loadActivityHistory = async (processInstanceId) => {
  try {
    const response = await axios.get(`${API_BASE_URL}/api/process/instance/${processInstanceId}/activities/history`)
    activityHistory.value = response.data
  } catch (error) {
    console.error('加载活动历史失败:', error)
    ElMessage.error('加载历史记录失败')
  }
}

const loadActiveTasks = async (instanceId) => {
  try {
    const response = await axios.get(`${API_BASE_URL}/api/process/instance/${instanceId}/tasks/active`)
    activeTasks.value = response.data
  } catch (error) {
    console.error('加载活动任务失败:', error)
    ElMessage.error('加载任务失败')
  }
}

const handleSearch = () => {
  pagination.current = 1
  loadProcessInstances()
}

const handleReset = () => {
  Object.assign(queryForm, {
    processInstanceId: '',
    processDefinitionKey: '',
    status: ''
  })
  pagination.current = 1
  loadProcessInstances()
}

const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  loadProcessInstances()
}

const handleCurrentChange = (current) => {
  pagination.current = current
  loadProcessInstances()
}

const handleViewDetail = async (instance) => {
  currentInstance.value = instance
  await loadProcessInstanceDetail(instance.id)
  await loadActivityHistory(instance.id)
  showProgressDialog.value = true
}

const handleViewTasks = async (instance) => {
  currentInstance.value = instance
  await loadActiveTasks(instance.id)
  showTaskDialog.value = true
}

const handleActivate = async (instance) => {
  try {
    await ElMessageBox.confirm('确定激活此流程实例吗？', '提示')
    await axios.post(`${API_BASE_URL}/api/process/instance/${instance.id}/activate`)
    ElMessage.success('激活成功')
    loadProcessInstances()
  } catch (error) {
    if (error.response) {
      ElMessage.error('激活失败')
    }
  }
}

const handleCompleteTask = (task) => {
  selectedTask.value = task
  completeForm.approved = true
  completeForm.comment = ''
}

const handleClaimTask = async (task) => {
  try {
    await ElMessageBox.confirm('确定认领此任务吗？', '提示')
    // 调用认领API - 这里需要根据实际API调整
    await axios.post(`${API_BASE_URL}/api/task/${task.id}/claim`, {
      assignee: currentUser.value
    })
    ElMessage.success('认领成功')
    if (currentInstance.value) {
      await loadActiveTasks(currentInstance.value.id)
    }
  } catch (error) {
    if (error.response) {
      ElMessage.error('认领失败')
    }
  }
}

const handleCompleteTaskSubmit = async () => {
  if (!completeForm.comment.trim()) {
    ElMessage.warning('请输入审批意见')
    return
  }

  submitting.value = true
  try {
    // 调用完成任务API
    await axios.post(`${API_BASE_URL}/api/task/${selectedTask.value.id}/complete`, {
      variables: {
        approved: completeForm.approved,
        comment: completeForm.comment
      }
    })

    ElMessage.success('处理成功')
    selectedTask.value = null
    if (currentInstance.value) {
      await loadActiveTasks(currentInstance.value.id)
    }
    loadProcessInstances() // 刷新实例列表
  } catch (error) {
    console.error('完成任务失败:', error)
    ElMessage.error('处理失败')
  } finally {
    submitting.value = false
  }
}

const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

const formatDuration = (milliseconds) => {
  if (!milliseconds) return ''
  const seconds = Math.floor(milliseconds / 1000)
  const minutes = Math.floor(seconds / 60)
  const hours = Math.floor(minutes / 60)

  if (hours > 0) {
    return `${hours}小时${minutes % 60}分钟`
  } else if (minutes > 0) {
    return `${minutes}分钟${seconds % 60}秒`
  } else {
    return `${seconds}秒`
  }
}

const formatVariables = (variables) => {
  if (!variables) return []
  return Object.keys(variables).map(key => ({
    name: key,
    value: JSON.stringify(variables[key])
  }))
}

const getStatusType = (instance) => {
  const types = {
    'active': 'success',
    'completed': 'info',
    'suspended': 'warning'
  }
  return types[instance.status] || 'info'
}

const getStatusText = (instance) => {
  const texts = {
    'active': '运行中',
    'completed': '已结束',
    'suspended': '已挂起'
  }
  return texts[instance.status] || '未知'
}

const getTimelineType = (activity) => {
  if (!activity.endTime) return 'success' // 当前节点
  return 'primary' // 已完成节点
}

const getActivityTagType = (activity) => {
  if (!activity.endTime) return 'success' // 当前节点
  return 'primary' // 已完成节点
}

const getCurrentActivity = () => {
  const current = activityHistory.value.find(activity => !activity.endTime)
  return current ? current.activityName : '无'
}
</script>

<style scoped>
.progress-container {
  max-height: 70vh;
  overflow-y: auto;
}

.bpmn-diagram {
  min-height: 300px;
  background: #f8f9fa;
}
</style>